using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using CodeStory.SmartUpload.WebControls;
using CodeStory.SmartUpload.WebControls;

namespace CodeStory.SmartUpload
{
	public class SmartUploadHttpModule : IHttpModule
	{
		public SmartUploadHttpModule() {
			//LoggingService.Info("New HttpModule created...");
		}
		#region IHttpModule Members

		public void Dispose() {
		}

		public void Init(HttpApplication context) {
			SmartService.InitializeSmartUpload();
			context.BeginRequest += new EventHandler(BeginRequest);
			context.EndRequest += new EventHandler(EndRequest);
			context.Error += new EventHandler(Error);
		}

		void BeginRequest(object sender, EventArgs e) {
			HttpApplication application = (HttpApplication)sender;

			SmartUploadContext.CreateContext(application.Context);
			SmartUploadContext c = SmartUploadContext.GetContext(application.Context);
			if (c != null) {
				c.SmartProgress.Status = UploadStatus.Initializing;
			}
			if (application.Context.Request.ContentType.IndexOf("multipart/form-data") <= -1) {
				return;
			}
			HttpWorkerRequest workerRequest = (HttpWorkerRequest)((IServiceProvider)HttpContext.Current).GetService(typeof(HttpWorkerRequest));	
			if (!workerRequest.HasEntityBody()) {
				return;
			}
			SmartUploadHelper helper = new SmartUploadHelper(application);
			helper.DoUpload();
		}

		void EndRequest(object sender, EventArgs e) {
			HttpApplication application = sender as HttpApplication;
			SmartUploadContext c = SmartUploadContext.GetContext(application.Context);
			if (c != null) {
				if (SmartConfiguration.AutoDeleteTempFiles) {
					foreach (UploadFile file in c.UploadFiles) {
						file.Delete();
					}
				}
				SmartUploadContext.RemoveContext(application.Context);
			}
		}

		void Error(object sender, EventArgs e) {
		}

		#endregion
	}
}
